﻿using System;
using System.Linq;
using System.Web.Mvc;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Core.Service;
using Icms.WebUI.Builder;
using Icms.WebUI.Dto;
using Omu.Awesome.Mvc;
using System.Web;

namespace Icms.WebUI.Controllers
{
    public class FileController : Crudere<File, FileCreateInput, FileEditInput>
    {
        private readonly IRepo<Case> caseRepo;
        private readonly IFileManagerService fileManagerService;
        private new readonly IFileService s;

        public FileController(IFileService s, IMapper<File, FileCreateInput> v, IMapper<File, FileEditInput> ve, IRepo<Case> caseRepo, IFileManagerService fileManagerService)
            : base(s, v, ve)
        {
            this.s = s;
            this.caseRepo = caseRepo;
            this.fileManagerService = fileManagerService;
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            if (file == null) return new EmptyResult();
            var name = fileManagerService.Save(file.InputStream, file.FileName);
            return Json(new {name, type = file.ContentType, size = file.ContentLength });
        }

        public ActionResult Download(Guid id)
        {
            var f = s.Get(id);
            HttpContext.Response.AddHeader("content-disposition","attachment; filename="+f.Name);
            return new FileStreamResult(fileManagerService.GetStream(f.Bytes), f.ContentType);
        }

        public override ActionResult Index()
        {
            ViewBag.Case = caseRepo.Get(new Guid(Request["CaseId"]));
            return View();
        }

        public virtual ActionResult Search(string title, int page = 1, int ps = 5)
        {
            var src = s.Where(o => true);
            var rows = this.RenderView("rows", src.Pag(page,ps));

            return Json(new { rows, more = src.Count() > page * ps });
        }
    }
}